package com.yuehuanghun.admin.core.controller.system;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.yuehuanghun.admin.core.config.UserConstants;
import com.yuehuanghun.admin.core.config.util.SecurityUtils;
import com.yuehuanghun.admin.core.config.util.UserUtils;
import com.yuehuanghun.admin.core.config.util.poi.ExcelUtil;
import com.yuehuanghun.admin.core.domain.SysRole;
import com.yuehuanghun.admin.core.domain.SysUser;
import com.yuehuanghun.admin.core.service.ISysPostService;
import com.yuehuanghun.admin.core.service.ISysRoleService;
import com.yuehuanghun.admin.core.service.ISysUserService;
import com.yuehuanghun.framework.annotation.Log;
import com.yuehuanghun.framework.annotation.Log.BusinessType;
import com.yuehuanghun.framework.domain.PageDTO;
import com.yuehuanghun.framework.exception.ValidateException;
import com.yuehuanghun.framework.util.Kv;
import com.yuehuanghun.framework.util.StringUtils;
import com.yuehuanghun.framework.util.WrapperHelper;
import com.yuehuanghun.framework.web.BaseResource;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;

/**
 * 用户信息
 * 
 * @author yadmin
 */
@RestController
@RequestMapping("/system/user")
@SaCheckLogin
public class SysUserController extends BaseResource {
	@Autowired
	private ISysUserService userService;

	@Autowired
	private ISysRoleService roleService;

	@Autowired
	private ISysPostService postService;

	/**
	 * 获取用户列表
	 */
	@GetMapping("/list")
	@SaCheckPermission("system:user:list")
	public PageDTO<SysUser> list(SysUser user) { //NOSONAR
		startPage();
		List<SysUser> list = userService.getUserList(user);
		return toPage(list);
	}

	@Log(title = "用户管理", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	@SaCheckPermission("system:user:export")
	public String export(SysUser user) { //NOSONAR
		List<SysUser> list = userService.getUserList(user);
		ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
		return util.exportExcel(list, "用户数据");
	}

	@Log(title = "用户管理", businessType = BusinessType.IMPORT)
	@PostMapping("/importData")
	@SaCheckPermission("system:user:import")
	public void importData(MultipartFile file, boolean updateSupport) throws Exception {
		ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
		List<SysUser> userList = util.importExcel(file.getInputStream());
		String operName = UserUtils.getCurrentUserName();
		String message = userService.importUser(userList, updateSupport, operName);
		WrapperHelper.setMessage(message);
	}

	@GetMapping("/importTemplate")
	public String importTemplate() {
		ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
		return util.importTemplateExcel("用户数据");
	}

	/**
	 * 根据用户编号获取详细信息
	 */
	@SuppressWarnings("rawtypes")
	@GetMapping(value = { "/", "/{userId}" })
	@SaCheckPermission("system:user:query")
	public Map getInfo(@PathVariable(value = "userId", required = false) Long userId) {
		Kv result = Kv.create();
		List<SysRole> roles = roleService.getRoleAll();
		result.set("roles", SysUser.isAdmin(userId) ? roles
				: roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
		result.set("posts", postService.getAll());
		if (StringUtils.isNotNull(userId)) {
			result.set("user", userService.getById(userId).orElse(null));
			result.set("postIds", postService.getPostIdsByUserId(userId).stream().map(item -> item.toString()).collect(Collectors.toList()));
			result.set("roleIds", roleService.getRolesByUserId(userId).stream().map(item -> item.getRoleId().toString()).collect(Collectors.toList()));					
		}
		return result;
	}

	/**
	 * 新增用户
	 */
	@Log(title = "用户管理", businessType = BusinessType.INSERT)
	@PostMapping
	@SaCheckPermission("system:user:add")
	public void add(@Validated @RequestBody SysUser user) { //NOSONAR
		if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
			throw new ValidateException("新增用户'" + user.getUserName() + "'失败，登录账号已存在"); //NOSONAR
		} else if (StringUtils.isNotEmpty(user.getPhonenumber())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			throw new ValidateException("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
		} else if (StringUtils.isNotEmpty(user.getEmail())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			throw new ValidateException("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		user.setDelFlag("0");
		user.setUserType("00");
		user.setAvatar("");
		userService.insertUser(user);
	}

	/**
	 * 修改用户
	 */
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping
	@SaCheckPermission("system:user:edit")
	public void edit(@Validated @RequestBody SysUser user) { //NOSONAR
		userService.checkUserAllowed(user);
		if (StringUtils.isNotEmpty(user.getPhonenumber())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			throw new ValidateException("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
		} else if (StringUtils.isNotEmpty(user.getEmail())
				&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			throw new ValidateException("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
		}
		userService.updateUser(user);
	}

	/**
	 * 删除用户
	 */
	@Log(title = "用户管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
	@SaCheckPermission("system:user:remove")
	public void remove(@PathVariable Long[] userIds) {
		userService.deleteUserByIds(userIds);
	}

	/**
	 * 重置密码
	 */
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping("/resetPwd")
	@SaCheckPermission("system:user:resetPwd")
	public void resetPwd(@RequestBody SysUser user) { //NOSONAR
		userService.checkUserAllowed(user);
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		user.setUpdateBy(UserUtils.getCurrentUserName());
		userService.updateById(user);
	}

	/**
	 * 状态修改
	 */
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping("/changeStatus")
	@SaCheckPermission("system:user:edit")
	public void changeStatus(@RequestBody SysUser user) { //NOSONAR
		userService.checkUserAllowed(user);
		user.setUpdateBy(UserUtils.getCurrentUserName());
		userService.updateById(user);
	}
}
